package com.muy.redis.common.tree.actions;

import com.intellij.icons.AllIcons;
import com.muy.redis.common.tree.MTTreeCell;
import com.muy.redis.common.tree.TreePanelMark;
import com.muy.redis.utils.JTreeUtils;
import com.muy.redis.utils.MrRedisConnectionUtils;
import com.muy.redis.utils.RedisPoolManager;
import com.muy.redis.view.window.redis.MrRedisTree;
import com.muy.redis.view.window.redis.bean.MrRedisConnectionParam;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisTopDb;

import javax.swing.tree.DefaultMutableTreeNode;

/**
 * @Author jiyanghuang
 * @Date 2022/8/4 21:10
 */
public class MrRedisCloseConnectionAction extends AbstractMTTreeCellSelectTreeAction {

    private TreePanelMark treePanelMark;

    public MrRedisCloseConnectionAction(TreePanelMark treePanelMark) {
        super("Close", "Close", AllIcons.Actions.Cancel, treePanelMark);
        this.treePanelMark = treePanelMark;
    }

    @Override
    public void handleSelectTree(DefaultMutableTreeNode mutableTreeNode, MTTreeCell mtTreeCell) {
        MrRedisTree mrRedisTree = (MrRedisTree) treePanelMark;
        if (mtTreeCell instanceof MTTreeCellMrRedisTopDb) {
            MTTreeCellMrRedisTopDb mtTreeCellMrRedisTopDb = (MTTreeCellMrRedisTopDb) mtTreeCell;
            MrRedisConnectionParam mrRedisConnectionParam = mtTreeCellMrRedisTopDb.getMrRedisConnectionParam();
            // 关闭连接池
            String connectionId = mrRedisConnectionParam.getId();
            RedisPoolManager redisPoolManager = MrRedisConnectionUtils.findRedisPoolManager(mrRedisConnectionParam);
            if (null != redisPoolManager) {
                redisPoolManager.invalidate();
            }

            // 关闭所有Editor
            MrRedisConnectionUtils.closeAllEditor(connectionId, mrRedisTree.getProject());

            // 清除connectionNode子节点
            mutableTreeNode.removeAllChildren();
            JTreeUtils.reload(mrRedisTree.jTree(), mutableTreeNode);
        }
    }
}
